package com.lcq.apktoolyml;

import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;

import java.io.*;
import java.nio.charset.StandardCharsets;

public class YmlUtil {
    /**
     * 加载apktool.yml 到ApktoolYml类中
     *
     * @param ymlPath apktool.yml文件路径
     * @return
     */
    public static ApktoolYml loadYml(String ymlPath) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(new File(ymlPath));
            return new Yaml().loadAs(fis, ApktoolYml.class);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 将ApktoolYml 实例写入apktool.yml文件
     *
     * @param data    ApktoolYml 实例
     * @param ymlPath apktool.yml文件路径
     */
    public static void write(ApktoolYml data, String ymlPath) {
        FileOutputStream fos = null;
        OutputStreamWriter outputStreamWriter = null;
        Writer writer = null;
        try {
            fos = new FileOutputStream(new File(ymlPath));
            outputStreamWriter = new OutputStreamWriter(fos, StandardCharsets.UTF_8);
            writer = new BufferedWriter(outputStreamWriter);
            DumperOptions options = new DumperOptions();
            options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
            new Yaml().dump(data, writer);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }
            if (outputStreamWriter != null) {
                try {
                    outputStreamWriter.close();
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }
        }
    }

    /**
     * @param srcYmlPath    需要合并的apktool.yml文件
     * @param targetYmlPath 合并到的目标apktool.yml文件
     */
    public void merge(String srcYmlPath, String targetYmlPath) {
        ApktoolYml mergeYml = loadYml(srcYmlPath);
        ApktoolYml targetYml = loadYml(targetYmlPath);
        targetYml.addDoNotCompress(mergeYml.doNotCompress);
        targetYml.putUnknownFiles(mergeYml.unknownFiles);
        write(targetYml, targetYmlPath);
    }
}
